﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Screenshot2Disk.Localization;
using System.IO;
using System.Drawing.Imaging;

namespace Screenshot2Disk
{
    public class OutputFormats {
        public static readonly string PNG  = "PNG";
        public static readonly string JPEG = "JPEG";

        public static readonly string CSV = "CSV";
        public static readonly string RTF = "RTF";
        public static readonly string HTML = "HTML";

        public static readonly string TEXT="TXT";

    }

    public class ClipboardFormat
    {
        public string Name { get; set; }
        public string[] Formats { get; set; }
        public string OutputFormat { get; set; }

        public override string ToString()
        {
            return this.Name;
        }

        public static ClipboardFormat[] GetSupportedFormats()
        {
            var data = Clipboard.GetDataObject();
            var clipboardFormats = data.GetFormats();
            var formats = from i in GetFormats()
                          where (from f in i.Formats where clipboardFormats.Contains(f) select f).Count() > 0
                          select i;
            return formats.ToArray();
        }

        private static ClipboardFormat[] GetFormats()
        {
            return new[]{
                    new ClipboardFormat { Name = "RTF", Formats = new[]{DataFormats.Rtf}, OutputFormat = OutputFormats.RTF},
                    new ClipboardFormat { Name = "HTML", Formats = new[]{DataFormats.Html}, OutputFormat = OutputFormats.HTML},
                    new ClipboardFormat { Name = "CSV", Formats = new[]{DataFormats.CommaSeparatedValue}, OutputFormat = OutputFormats.CSV},

                    new ClipboardFormat { Name = "Text", Formats = new[]{DataFormats.StringFormat, DataFormats.UnicodeText, DataFormats.Text}, OutputFormat =OutputFormats.TEXT},

                    new ClipboardFormat { Name = "Image", Formats = new []{DataFormats.EnhancedMetafile, DataFormats.MetafilePict, /*DataFormats.Bitmap, */DataFormats.Tiff , DataFormats.Dib}, OutputFormat = OutputFormats.PNG},
                    
            };
        }
    }

  
    public class ClipboardHelper
    {
        const string OUTPUTFORMAT = "{0:yyyy-MM-dd HH-mm-ss}.{1}";

        public static void Handle(string path, ClipboardFormat format)
        {
            CheckDir(path);

            var data = Clipboard.GetDataObject();
            var intputFormat = format.Formats.Where(f => data.GetDataPresent(f)).FirstOrDefault();
            var rawdata = data.GetData(intputFormat);

            if (format.OutputFormat == OutputFormats.HTML)
            {
                var html = rawdata as string;
                if (html != null && html.IndexOf("<") > 0)
                    html = html.Substring(html.IndexOf("<"));

                SimpleText(path, ".htm", html);
                return;
            }

            if (format.OutputFormat == OutputFormats.TEXT)
            {
                SimpleText(path, ".txt", rawdata as string);
                return;
            }

            if (format.OutputFormat == OutputFormats.RTF)
            {
                SimpleText(path, ".rtf", rawdata as string);
                return;
            }

            if (format.OutputFormat == OutputFormats.CSV)
            {
                if (rawdata is string)
                    SimpleText(path, ".csv", rawdata as string);
                else if (rawdata is MemoryStream)
                    SimpleWrite(path, ".csv", rawdata as MemoryStream);
                return;
            }

            if (format.OutputFormat == OutputFormats.PNG)
            {
                HandlePNG(path);
                return;
            }
        }

        private static void SimpleWrite(string path, string p, MemoryStream memoryStream)
        {
            var filename = GetFilename(path, p);

            using (var fs = File.Open(filename, FileMode.CreateNew, FileAccess.Write))
            {
                int read = 0;
                byte[] buf = new byte[2048];
                while((read = memoryStream.Read(buf, 0,buf.Length)) > 0)
                    fs.Write(buf, 0, read);
            }
        }

        private static void SimpleText(string path, string extension, string text)
        {
            var filename = GetFilename(path, extension);
            File.WriteAllText(filename, text);
        }
      
        private static void CheckDir(string path)
        {
            if (!Directory.Exists(path))
                throw new Exception(string.Format(Strings.DirectoryNotFound, path));
        }

        private static void HandlePNG(string path)
        {
            using (var img = Clipboard.GetImage())
            {
                var filename = GetFilename(path, ".png");
                img.Save(filename, ImageFormat.Png);
            }
        }

        private static string GetFilename(string path, string ext)
        {
            while (ext.StartsWith("."))
                ext = ext.Substring(1);

            var filename = string.Format(OUTPUTFORMAT, DateTime.Now, ext);
            return Path.Combine(path, filename);
        }
    }
}
